package com.hotel.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hotel.bean.RespBean;
import com.hotel.bean.Room;
import com.hotel.bean.User;
import com.hotel.exception.SteduException;
import com.hotel.service.RoomService;
import com.hotel.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping("/admin/room")
public class RoomController {
    @Autowired
    private RoomService roomService;
    @Autowired
    private UserService userService;

    //退房
    @PutMapping("/{rnumber}")
    public RespBean updateUserAndRoomState(@PathVariable String rnumber) throws SteduException {
        if (!roomService.updateUserUstate(rnumber)) {
            throw new SteduException("出错了请联系管理员");
        }
        return RespBean.ok("退房成功");
    }

    //修改
    @PutMapping
    public RespBean update(@RequestBody @Validated Room room) throws SteduException {
        if (roomService.update(room)) {
            return RespBean.ok("修改成功");
        }
        return RespBean.error("修改失败,请联系管理员");
    }

    //删除
    @DeleteMapping("/{rnumber}")
    public RespBean delectByRnumber(@PathVariable String rnumber) throws SteduException {
        if (roomService.deleteByRnumber(rnumber)) {
            return RespBean.ok("删除成功");
        }
        return RespBean.error("删除失败,请联系管理员");
    }

    //根据房号查询
    @GetMapping("/{rnumber}")
    public RespBean selectByRnumber(@PathVariable String rnumber) {
        if (roomService.selectByRnumber(rnumber) != null) {
            return RespBean.ok("", roomService.selectByRnumber(rnumber));
        }
        return RespBean.error("房间号不存在");
    }

    //查询所有
    @GetMapping
    public RespBean selectAll(Integer pageNum, String rnumber,Integer rstate) {
        if (pageNum == null) {
            pageNum = 1;
        }
        PageHelper.startPage(pageNum, 5);
        List<Room> rooms = roomService.selectAll(rnumber,rstate);
        PageInfo<Room> info = new PageInfo<>(rooms);
        return RespBean.ok("查询成功", info);
    }

    //查询特定房间的所有的用户
    @GetMapping("/alluid/{rid}")
    public RespBean selectUidByRid(@PathVariable Integer rid) {
        List<Integer> uidList = roomService.selectUidByRid(rid);
        List<User> users = uidList.stream().map(e -> userService.selectByUid(e)).collect(Collectors.toList());
        return RespBean.ok("", users);
    }
}

